import React, { useEffect, useState } from 'react'
import FormRender, { useForm } from 'form-render';
import { message, Cascader } from 'antd';
import { getCustomFrom } from '@/request/basicSettings'
import { useLocation } from 'react-router-dom'
import { dictionary } from '@/request/basicSettings'
// import fun from '@/utils/CustomFromConfig'
/**
 * getDom 获取dom
 * onFinish 提交后回调
 * form.submit 提交事件
 * form.setValues 修改值
 * mode 获取表单类型分类
 * selectList下拉数据
 * type页面分类
 * dictionaryName分类类型
 * **/
interface PropsType {
    [propsName: string]: any
}
function CustomFrom(props: PropsType) {
    const objName = props.objName ? props.objName + '.' : ''
    //自定义组件配置
    const config = {
        area: {
            title: '地址',
            displayType: 'row',
            props: {
                options: props.selectList,
                fieldNames: { label: 'name', value: 'name' }
            },
            type: 'array',
            widget: 'cascader',
            width: "100%",
            required: true,
        }
    }
    const location = useLocation()
    const form = useForm()
    const [schema, setSchema]: any = useState({});
    const reg = new RegExp('/home')
    const path = location.pathname.replace(reg, '') //当前路由
    //获取下拉分类
    const getGoodType = async (callBack: any, id?: any) => {
        const res = await dictionary({
            type: props.dictionaryName,
            id: id
        })
        callBack(res.data.pub)
    }
    //获取表单数据
    const getCustomFromDate = async () => {
        if (path) {
            const res = await getCustomFrom({
                describe: path,
                type: props.mode || 'type'
            })
            if (!res.data.length) return
            const text = JSON.parse(res.data[0].text)
            setSchema(text)
        }
    }
    //提交
    const onFinish = (data: any, errors: any) => {
        data = form.formData
        if (errors.length > 0) {
            message.error(
                '校验未通过：' + JSON.stringify(errors.map((item: any) => item.name))
            );
        }
        props?.onFinish(data, errors)
    }
    //下拉选择
    const onChange = (value: any) => {
        if (props.type.includes('store')) {
            setValues(`${objName}type`, value)
            getGoodType((v: any) => {
                form.setSchemaByPath(`${objName}breed`, {
                    props: {
                        ...setOptions(v)
                    }
                })
                setValues(`${objName}breed`, v.length ? v[0].nid : null)
            }, value)
        }
    }
    //修改自定义配置
    const setOptions = (op: any[], fieldNames = { label: 'text', value: 'nid' }) => {
        return {
            options: op,
            fieldNames: fieldNames
        }
    }
    //根据路径修改自定义组件值
    const setValues = (url: string, value: any) => {
        return form.setValueByPath(url, value)
    }
    //过滤下拉列表数据
    const filterSelectList = (arr: any[], name = 'store_name', value = 'id') => {
        const names = arr.map(v => v[name])
        const values = arr.map(v => v[value])
        return {
            enum: values,
            enumNames: names
        }
    }
    //init
    const init = async (text: any) => {
        if (!text.properties) return
        if (props.type.includes('goods')) {    //商品分类
            await getGoodType((v: any) => {
                form.setSchemaByPath(`${objName}type`, {
                    props: {
                        onChange: (e: any) => onChange(e),
                        ...setOptions(v)
                    }
                })
            })
        }
        if (props.type.includes('area')) {    //省市区

            text.properties.area = config.area
            form.setSchemaByPath(`${objName}area`, config.area)
        }

        if (props.type.includes('store')) {
            form.setSchemaByPath(`${objName}store_id`, {//店铺下拉
                type: 'number',
                ...filterSelectList(props.selectList)
            })
            setValues(`${objName}store_id`, props.selectList.length ? props.selectList[0].id : null)
        }
        if (props.defaultValues) {
            setValues(`${objName.split('.')[0]}`, props.defaultValues)
            if (props.type.includes('store')) {
                onChange(props.defaultValues.type)
            }
        }
    }
    useEffect(() => {
        if (form) init(schema)
    }, [schema])
    useEffect(() => {
        getCustomFromDate()
        props?.getDom(form)
    }, [])
    return (
        <div>
            <FormRender form={form}
                schema={schema} onFinish={onFinish}
                onMount={props?.onMount}
                widgets={{ cascader: Cascader }}
            />
        </div>
    )
}

export default CustomFrom